package cc.linker.steplink.crm.merchant.service;

import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.commons.utils.NumberUtils;
import cc.linker.steplink.crm.merchant.dao.RefundDao;
import cc.linker.steplink.crm.merchant.dao.ShopOrderMapper;
import cc.linker.steplink.crm.merchant.pojo.Express;
import cc.linker.steplink.crm.merchant.pojo.OrderGoods;
import cc.linker.steplink.crm.merchant.pojo.ShopOrder;
import cc.linker.steplink.crm.merchanth5.dao.MallBoomDao;
import cc.linker.steplink.crm.merchanth5.dao.acs.ProtectRecordDao;
import cc.linker.steplink.crm.merchanth5.dao.acs.PurchaseProcessDao;
import cc.linker.steplink.crm.merchanth5.pojo.acs.RefundParamPo;
import cc.linker.steplink.crm.merchanth5.service.acs.PurchaseProcessService;
import cc.linker.steplink.crm.merchanth5.service.redis.MerchantService;
import cc.linker.steplink.crm.response.GlobalException;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class ShopOrderService {

    @Autowired
    private ShopOrderMapper shopOrderMapper;
    @Autowired
    private MallBoomDao mallBoomDao;
    @Autowired
    private RefundDao refundDao;
    @Autowired
    private ProtectRecordDao protectRecordDao;
    @Autowired
    private PurchaseProcessDao purchaseProcessDao;
    @Autowired
    private PurchaseProcessService purchaseProcessService;
    @Autowired
    private RefundService refundService;
    @Autowired
    private SystemProperties systemProperties;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MerchantService merchantService;

    public String getMallsCustomerIdByMallsName(String mallsName){
        return shopOrderMapper.getMallsCustomerIdByMallsName(mallsName);
    }

    public List<ShopOrder> list(Map<String, Object> params) {
        // 当前用户
        String belongId = params.get("belongId").toString();
        List<ShopOrder> orderList = shopOrderMapper.getOrderList(params);
        for (ShopOrder order : orderList) {
            String addressPhone = order.getAddressPhone();
            if (StringUtils.isEmpty(addressPhone)) {
                String customerId = order.getCustomerId();
                String bindPhone = mallBoomDao.getBindPhoneByCid(customerId);
                order.setAddressPhone(bindPhone);
            }
            String createTime = order.getCreateTime();
            if (createTime.contains(".")) {
                String substring = createTime.substring(0, createTime.length() - 2);
                order.setCreateTime(substring);
            }
            //  订单类型
            String orderType = "";

            if(99 == order.getOrderGoodsType()){
                orderType = "/积分兑换订单";
                order.setOrderGoodsType2(4);
            }else{
                if (1 == order.getIsVirtual()) {
                    // 虚拟商品订单类
                    order.setOrderGoodsType(7);
                    orderType = orderType + "/" + "虚拟商品订单";
                }else {
                    if (1 == order.getOrderGoodsType()) {
                        // 实物订单
                        orderType = orderType + "/" + "实物订单";
                    } else {
                        // 课程订单
                        orderType = orderType + "/" + "课程订单";
                    }
                }
                order.setOrderGoodsType2(0);
                // 供货商品
                Map<String, Object> merchantDetail = new HashMap<>();
                if (belongId.equals(order.getSalerBelongId())
                        && !StringUtils.isEmpty(order.getMallsBelongId())) {
                    // 推广订单
                    merchantDetail = merchantService.getMallDetail(order.getMallsBelongId(), order.getOrgId());
                    orderType = orderType + "/" + "推广订单";
                    order.setOrderGoodsType2(1);
                }
                if (belongId.equals(order.getMallsBelongId())) {
                    // 供货订单
                    String SalerBelongId="";
                    if(!StringUtils.isEmpty(order.getSalerBelongId()) && !order.getSalerBelongId().equals(order.getOrgId())){
                        SalerBelongId = order.getSalerBelongId();
                    }
                    merchantDetail = merchantService.getMerchantDetail(SalerBelongId, order.getOrgId());
                    orderType = orderType + "/" + "供货订单";
                    order.setOrderGoodsType2(2);
                }
                if (!belongId.equals(order.getSalerBelongId())
                        && !belongId.equals(order.getMallsBelongId())) {
                    merchantDetail = merchantService.getMerchantDetail(order.getSalerBelongId(), order.getOrgId());
                    orderType = orderType + "/" + "联盟商家订单";
                    order.setOrderGoodsType2(3);
                }
                if (StringUtils.isEmpty(orderType)) {
                    orderType = "/";
                }
                order.setMerchantDetail(merchantDetail);
            }
            order.setOrderType(orderType.substring(1));

            // 供货名称
            String supplyName = "";
            if (3 == order.getOrderGoodsType2() || 2 == order.getOrderGoodsType2()) {
                if(2 == order.getOrderGoodsType2() && !StringUtils.isEmpty(order.getSalerBelongId()) && order.getSalerBelongId().equals(order.getOrgId())){
                    //大b
                    supplyName = shopOrderMapper.getSalerNameByOrgId(order.getOrgId());
                }else {
                    // 联盟商家订单
                    supplyName = shopOrderMapper.getSalerNameByCustomerId(order.getSalerBelongId());
                }
            } else if (1 == order.getOrderGoodsType2()) {
                // 推广订单
                supplyName = shopOrderMapper.getMallsNameByCustomerId(order.getMallsBelongId());
            }
            order.setSupplyName(supplyName);
            //  订单商品
            params.put("orderId", order.getOrderId());
            params.put("orderGoodsType",order.getOrderGoodsType2());
            List<OrderGoods> orderGoodsList;
            if(99 == order.getOrderGoodsType()){
                orderGoodsList = shopOrderMapper.getIntegralOrderGoodsList(params);
            }else{
                orderGoodsList = shopOrderMapper.getOrderGoodsList(params);
            }
            if (orderGoodsList != null && orderGoodsList.size() > 0) {
                for (OrderGoods orderGoods : orderGoodsList) {
                    // 撤销退款状态改为7
                    if (orderGoods.getRefundStatus() != null
                            && orderGoods.getRefundStatus() == 0
                            && !StringUtils.isEmpty(orderGoods.getProtectCode())) {
                        orderGoods.setRefundStatus(7);
                    }
                }
            }
            order.setGoodsList(orderGoodsList);
        }
        return orderList;
    }

    public int remark(Map<String, Object> params) {
        if("2".equals(params.get("orderType").toString())){
            return shopOrderMapper.remarkIntegral(params);
        }else{
            return shopOrderMapper.remark(params);
        }
    }

    public int delivery(Map<String, Object> params) {
        if("2".equals(params.get("orderType").toString())){
            shopOrderMapper.deliveryIntegral(params);
            int count = shopOrderMapper.getNotDeliveryCountIntegral(params);
            if (count == 0) {
                shopOrderMapper.updateOrderStatusIntegral(params);
            }
            return count;
        }else{
            shopOrderMapper.delivery(params);
            int count = shopOrderMapper.getNotDeliveryCount(params);
            if (count == 0) {
                shopOrderMapper.updateOrderStatus(params);
            }
            return count;
        }
    }

    public Map<String, Object> getMsgInfo(Map<String, Object> params) {
        if("2".equals(params.get("orderType").toString())){
            return shopOrderMapper.getMsgInfoIntegral(params);
        }else{
            return shopOrderMapper.getMsgInfo(params);
        }
    }

    public List<Express> getExpress() {
        return shopOrderMapper.getExpress();
    }

    public ShopOrder getOrder(Map<String, Object> params) {
        ShopOrder ret;
        if(params.get("orderSn").toString().startsWith("I")){
            ret = shopOrderMapper.getIntegralOrder(params);
        }else{
            ret = shopOrderMapper.getOrder(params);
        }
        String addressPhone = ret.getAddressPhone();
        if (StringUtils.isEmpty(addressPhone)) {
            String customerId = ret.getCustomerId();
            String bindPhone = mallBoomDao.getBindPhoneByCid(customerId);
            ret.setAddressPhone(bindPhone);
        }
        String createTime = ret.getCreateTime();
        if (createTime.contains(".")) {
            String substring = createTime.substring(0, createTime.length() - 2);
            ret.setCreateTime(substring);
        }
        String paymentTime = StringUtils.isEmpty(ret.getPaymentTime()) ? "" : ret.getPaymentTime();
        if (paymentTime.contains(".")) {
            String substring = paymentTime.substring(0, paymentTime.length() - 2);
            ret.setPaymentTime(substring);
        }
        String deliveryTime = StringUtils.isEmpty(ret.getDeliveryTime()) ? "" : ret.getDeliveryTime();
        if (deliveryTime.contains(".")) {
            String substring = deliveryTime.substring(0, deliveryTime.length() - 2);
            ret.setDeliveryTime(substring);
        }
        String finnshedTime = StringUtils.isEmpty(ret.getFinnshedTime()) ? "" : ret.getFinnshedTime();
        if (finnshedTime.contains(".")) {
            String substring = finnshedTime.substring(0, finnshedTime.length() - 2);
            ret.setFinnshedTime(substring);
        }
        String customerId = ret.getPName();
        String pName = mallBoomDao.getPNameByCustomerId(customerId);
        String bindPhone = mallBoomDao.getBindPhoneByCid(customerId);
        ret.setPName(pName);
        ret.setBindPhone(bindPhone);
        // 计算订单类型
        String mallsBelongId = ret.getMallsBelongId();
        String salerBelongId = ret.getSalerBelongId();
        String belongId = params.get("belongId").toString();
        String orderType = "";
        if(99 == ret.getOrderGoodsType()){
            orderType = "积分兑换订单";
            ret.setOrderGoodsType2(4);
        }else{
            if (1 == ret.getIsVirtual()) {
                // 虚拟商品订单类
                ret.setOrderGoodsType(7);
                orderType = orderType + "/" + "虚拟商品订单";
            }
            if (1 == ret.getOrderGoodsType()) {
                // 实物订单
                orderType = orderType + "/" + "实物订单";
            } else {
                // 课程订单
                orderType = orderType + "/" + "课程订单";
            }
            // 供货商品
            ret.setOrderGoodsType2(0);
            if (belongId.equals(salerBelongId) && !StringUtils.isEmpty(mallsBelongId)) {
                // 推广订单
                orderType = orderType + "/" + "推广订单";
                ret.setOrderGoodsType2(1);
            }
            if (belongId.equals(mallsBelongId)) {
                // 供货订单
                orderType = orderType + "/" + "供货订单";
                ret.setOrderGoodsType2(2);
            }
            if (!belongId.equals(salerBelongId) && !belongId.equals(mallsBelongId)) {
                orderType = orderType + "/" + "联盟商家订单";
                ret.setOrderGoodsType2(3);
            }
        }
        ret.setOrderType(orderType);
        Long orderId = ret.getOrderId();
        params.put("orderId", orderId);
        StringBuilder expressName = new StringBuilder();
        int shippingType = 0;
        params.put("orderGoodsType", ret.getOrderGoodsType2());

        List<OrderGoods> orderGoodsList;
        if(params.get("orderSn").toString().startsWith("I")){
            orderGoodsList = shopOrderMapper.getIntegralOrderGoodsList(params);
        }else{
            orderGoodsList = shopOrderMapper.getOrderGoodsList(params);
        }
        ret.setGoodsList(orderGoodsList);
        List<OrderGoods> goodsPos = ret.getGoodsList();
        for (OrderGoods po : goodsPos) {
            if (po.getShippingCode() != null) {
                expressName.append(po.getExpressName()).append(";");
            }
            if (po.getShippingType() == 1) {
                shippingType = 1;
            }
        }
        if (expressName.length() > 1) {
            expressName.deleteCharAt(expressName.length() - 1);
        }
        ret.setShippingType(shippingType);
        ret.setExpressName(expressName.toString());
        return ret;
    }

    public Object getOrderExpress(String orderSn) {
        if(StringUtils.isEmpty(orderSn)){
            throw GlobalException.build("参数错误");
        }
        Integer orderId;
        List<Map<String, Object>> result;
        if(orderSn.startsWith("I")){
            orderId = shopOrderMapper.getIntegralOrderIdByOrderSn(orderSn);
            result = shopOrderMapper.getIntegralOrderExpress(orderId);
        }else{
            orderId = shopOrderMapper.getOrderIdByOrderSn(orderSn);
            // 获取每个商品的快递信息
            result = shopOrderMapper.getOrderExpress(orderId);
        }
        List<Map<String, Object>> temps = new ArrayList<>();
        Map<String, List<Map<String, Object>>> glist =
                result.stream().collect(Collectors.groupingBy(e -> e.get("shippingCode").toString() + "_" + e.get("expressName").toString()));
        glist.forEach(
                (k, slist) -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("shippingCode", slist.get(0).get("shippingCode"));
                    map.put("shippingTime", slist.get(0).get("shippingTime"));
                    map.put("expressName", slist.get(0).get("expressName"));
                    map.put("goodsList", slist);
                    temps.add(map);
                });

        temps.sort((o1, o2) -> {
            String name1 = (String)o1.get("expressName");
            String name2 = (String)o2.get("expressName");
            return name1.compareTo(name2);
        });
        return temps;
    }

    public int closeOrder(Map<String, Object> params) {
        return shopOrderMapper.closeOrder(params);
    }

    public Map getOrderInfoById(Long orderId, Integer payMode,Integer orderType) {
        if (orderType.equals(1)) {
            return shopOrderMapper.getOrderInfoById(orderId, payMode);
        } else {
            return shopOrderMapper.getIntegralOrderInfoById(orderId);
        }
    }

    public void exportList(
            Map<String, Object> params, HttpServletResponse response, Integer payMode) {
        String belongId = params.get("belongId").toString();
        List<ShopOrder> orderList = shopOrderMapper.getOrderList(params);
        for (ShopOrder order : orderList) {
            String createTime = order.getCreateTime();
            if (createTime.contains(".")) {
                String substring = createTime.substring(0, createTime.length() - 2);
                order.setCreateTime(substring);
            }
            String orderType = "";
            if(99 == order.getOrderGoodsType()){
                orderType = "/积分兑换订单";
                order.setOrderGoodsType2(4);
                String orderTotalPrice = order.getOrderTotalPrice();
                if(!StringUtils.isEmpty(orderTotalPrice)){
                    if(Double.valueOf((orderTotalPrice.replace(",","")))>0){
                        orderTotalPrice = Double.valueOf((orderTotalPrice.replace(",","")))+"元";
                    }else {
                        orderTotalPrice="";
                    }
                }
                order.setOrderTotalPrice(orderTotalPrice);

            }else{
                order.setOrderTotalPrice(order.getOrderTotalPrice()+"元");
                if (1 == order.getIsVirtual()) {
                    // 虚拟商品订单类
                    order.setOrderGoodsType(7);
                    orderType = orderType + "/" + "虚拟商品订单";
                }else {
                    if (1 == order.getOrderGoodsType()) {
                        // 实物订单
                        orderType = orderType + "/" + "实物订单";
                    } else {
                        // 课程订单
                        orderType = orderType + "/" + "课程订单";
                    }
                }

                order.setOrderGoodsType2(0);
                // 供货商品
                if (belongId.equals(order.getSalerBelongId())
                        && !StringUtils.isEmpty(order.getMallsBelongId())) {
                    // 推广订单
                    orderType = orderType + "/" + "推广订单";
                    order.setOrderGoodsType2(1);
                }
                if (belongId.equals(order.getMallsBelongId())) {
                    // 供货订单
                    orderType = orderType + "/" + "供货订单";
                    order.setOrderGoodsType2(2);
                }
                if (!belongId.equals(order.getSalerBelongId())
                        && !belongId.equals(order.getMallsBelongId())) {
                    orderType = orderType + "/" + "联盟商家订单";
                    order.setOrderGoodsType2(3);
                }
                if (StringUtils.isEmpty(orderType)) {
                    orderType = "/";
                }
            }
            order.setOrderType(orderType.substring(1));
            // 供货名称
            String supplyName = "";
            if (3 == order.getOrderGoodsType2()) {
                // 联盟商家订单
                supplyName = shopOrderMapper.getSalerNameByCustomerId(order.getSalerBelongId());
            } else if (1 == order.getOrderGoodsType2()) {
                // 推广订单
                supplyName = shopOrderMapper.getMallsNameByCustomerId(order.getMallsBelongId());
            }
            order.setSupplyName(supplyName);
            //
            params.put("orderId", order.getOrderId());
            params.put("orderGoodsType",order.getOrderGoodsType2());

            List<OrderGoods> orderGoodsList;
            if(99 == order.getOrderGoodsType()){
                orderGoodsList = shopOrderMapper.getIntegralOrderGoodsList(params);
            }else{
                orderGoodsList = shopOrderMapper.getOrderGoodsList(params);
            }
            order.setGoodsList(orderGoodsList);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
        String date = sdf.format(new Date());
        String title = "订单" + date;
        try {
            exportRegisterXls(title, response, orderList, payMode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void exportRegisterXls(
            String title1, HttpServletResponse response, List<ShopOrder> orderList, Integer payMode)
            throws Exception {
        // 第一步，创建一个HSSFWorkbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();

        // 第二步，在workbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet(title1);
        for (int i = 0; i < 47; i++) {
            sheet.setColumnWidth(i, 256 * 20 + 184);
        }
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
        HSSFRow row = sheet.createRow(0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle cellStyle = wb.createCellStyle();
        // 设置背景色
        cellStyle.setFillForegroundColor((short) 13);
        cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

        cellStyle.setBottomBorderColor(IndexedColors.BLACK.index);
        cellStyle.setTopBorderColor(IndexedColors.BLACK.index);
        cellStyle.setLeftBorderColor(IndexedColors.BLACK.index);
        cellStyle.setRightBorderColor(IndexedColors.BLACK.index);
        // 下边框
        cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        // 左边框
        cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 上边框
        cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 右边框
        cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);

        // HSSFCellStyle style = wb.createCellStyle();
        // 创建一个居中格式
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        HSSFCellStyle cellStyleR = wb.createCellStyle();
        cellStyleR.setBottomBorderColor(IndexedColors.BLACK.index);
        cellStyleR.setTopBorderColor(IndexedColors.BLACK.index);
        cellStyleR.setLeftBorderColor(IndexedColors.BLACK.index);
        cellStyleR.setRightBorderColor(IndexedColors.BLACK.index);
        cellStyleR.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        cellStyleR.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        cellStyleR.setBorderTop(HSSFCellStyle.BORDER_THIN);
        cellStyleR.setBorderRight(HSSFCellStyle.BORDER_THIN);

        // HSSFCellStyle style = wb.createCellStyle();
        // 创建一个居中格式
        cellStyleR.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        HSSFFont font = wb.createFont();
        font.setFontName("黑体");
        // 设置字体大小
        font.setFontHeightInPoints((short) 14);
        cellStyle.setFont(font);
        // 声明列对象
        HSSFCell cell = null;
        String[] title = {
                "商品名称", "单价", "数量", "规格", "售后", "商品总价", "收货人", "收货人电话", "收货人地址", "实付金额", "订单状态", "订单类型",
                "订单号", "下单时间","供货商","备注"
        };
        // 创建标题
        for (int i = 0; i < title.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(cellStyle);
        }
        for (int i = 0; i < title.length; i++) {
            Integer startrow = 0;
            Integer overrow = 0;
            Integer startcol = i;
            Integer overcol = i;
            sheet.addMergedRegion(new CellRangeAddress(startrow, overrow, startcol, overcol));
        }

        int count = 1;
        for (ShopOrder order : orderList) {
            List<OrderGoods> goodslist = order.getGoodsList();
            if (goodslist != null && goodslist.size() > 0) {
                int starcount = count;
                int endcount = count + goodslist.size() - 1;
                row = sheet.createRow(count);
                cell = row.createCell(5);
                cell.setCellStyle(cellStyleR);
                String ordertotalString = order.getOrderTotalPrice();
                if(order.getPaymentPoints()>0){
                    if("".equals(ordertotalString)){
                        ordertotalString = order.getPaymentPoints()+"积分";
                    }else {
                        ordertotalString = order.getPaymentPoints()+"积分+"+ordertotalString;
                    }

                }
                if(order.getOrderGoodsType()==7){
                    order.setRealName("");
                    order.setAddressPhone("");
                }
                cell.setCellValue(ordertotalString);
                cell = row.createCell(6);
                cell.setCellStyle(cellStyleR);
                cell.setCellValue(order.getRealName());
                cell = row.createCell(7);
                cell.setCellStyle(cellStyleR);
                cell.setCellValue(order.getAddressPhone());
                cell = row.createCell(8);
                String address = "";
                if (!StringUtils.isEmpty(order.getProvinceName())) {
                    address = address + order.getProvinceName();
                }
                if (!StringUtils.isEmpty(order.getCityName())) {
                    address = address + order.getCityName();
                }
                if (!StringUtils.isEmpty(order.getAreaName())) {
                    address = address + order.getAreaName();
                }
                if (!StringUtils.isEmpty(order.getDetailedAddress())) {
                    address = address + order.getDetailedAddress();
                }
                if(order.getOrderGoodsType()==7){
                    address = "";
                }
                cell.setCellValue(address);
                cell = row.createCell(9);
                cell.setCellStyle(cellStyleR);
                String shippingFee = order.getShippingFee();
                if(StringUtils.isEmpty(shippingFee)){
                    shippingFee = "0.00";
                }
                cell.setCellValue(order.getOrderTotalPrice() + "(含运费：" + shippingFee + ")");
                cell = row.createCell(10);
                cell.setCellStyle(cellStyleR);
                String orderStatus = "";
                switch (order.getStatus()) {
                    case 0:
                        orderStatus = "已关闭";
                        break;
                    case 10:
                        orderStatus = "待付款";
                        break;
                    case 20:
                        orderStatus = "待发货";
                        break;
                    case 30:
                        orderStatus = "待收货";
                        break;
                    case 40:
                        orderStatus = "交易完成";
                        break;
                    case 50:
                        orderStatus = "已提交";
                        break;
                    case 60:
                        orderStatus = "已确认";
                        break;
                }
                cell.setCellValue(orderStatus);
                cell = row.createCell(11);
                cell.setCellStyle(cellStyleR);
                // 数据库中没有字段
                if (order.getOrderRebate() == null) {
                    order.setOrderRebate(0);
                }
                //                cell.setCellValue(order.getOrderGoodsType() == 1 ? "普通订单" : "课程订单");
                cell.setCellValue(order.getOrderType());
                cell = row.createCell(12);
                cell.setCellStyle(cellStyleR);
                cell.setCellValue(order.getOrderSn());
                cell = row.createCell(13);
                cell.setCellStyle(cellStyleR);
                cell.setCellValue(order.getCreateTime());
                cell = row.createCell(14);
                cell.setCellStyle(cellStyleR);
                cell.setCellValue(order.getSupplyName());
                cell = row.createCell(15);
                cell.setCellStyle(cellStyleR);
                cell.setCellValue(order.getBuyerRemark());

                for (int j = 0; j < goodslist.size(); j++) {
                    if (j > 0) {
                        row = sheet.createRow(count);
                    }
                    // 前四个是商品的信息
                    cell = row.createCell(0);
                    cell.setCellStyle(cellStyleR);
                    cell.setCellValue(goodslist.get(j).getGoodsName());
                    cell = row.createCell(1);
                    cell.setCellStyle(cellStyleR);
                    String goodsPrice="";
                    if(99 == order.getOrderGoodsType()){
                        goodsPrice = goodslist.get(j).getGoodsIntegral() + "积分";
                        if(goodslist.get(j).getGoodsPrice()!=null){
                            Double price = Double.valueOf(goodslist.get(j).getGoodsPrice().replaceAll(",",""));
                            if(price>0){
                                goodsPrice = goodsPrice + "+ ¥"+goodslist.get(j).getGoodsPrice();
                            }
                        }
                    }else{
                        goodsPrice = goodslist.get(j).getGoodsPrice() + "元";
                    }
                    cell.setCellValue(goodsPrice);
                    cell = row.createCell(2);
                    cell.setCellStyle(cellStyleR);
                    cell.setCellValue(goodslist.get(j).getGoodsNum());
                    cell = row.createCell(3);
                    cell.setCellStyle(cellStyleR);
                    cell.setCellValue(goodslist.get(j).getSkuInfo());
                    cell = row.createCell(4);
                    cell.setCellStyle(cellStyleR);
                    String refundStatus = "";
                    // 0未申请退款 1申请退款 2等待发货 3等待收货 4拒绝收货 5同意退款 6退款成功 7退款失败',
                    // (1）用户发起维权：用户对商品发起维权并维权没有结束或者关闭
                    // （2）维权结束：完成退款
                    // （3）维权关闭：维权撤销
                    // （4）空：用户没有发起过退款
                    switch (goodslist.get(j).getRefundStatus()) {
                        case 1:
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                            refundStatus = "用户发起维权";
                            break;
                        case 6:
                            refundStatus = "维权结束";
                            break;
                        case 7:
                            refundStatus = "维权关闭";
                            break;
                        case 0:
                            refundStatus = "";
                            break;
                    }
                    cell.setCellValue(refundStatus);
                    count++;
                }
                for (int i = 5; i < 16; i++) {
                    CellRangeAddress region = new CellRangeAddress(starcount, endcount, i, i);
                    sheet.addMergedRegion(region);
                    // 下边框   左边框  有边框  上边框
                    RegionUtil.setBorderBottom(1, region, sheet, wb);
                    RegionUtil.setBorderLeft(1, region, sheet, wb);
                    RegionUtil.setBorderRight(1, region, sheet, wb);
                    RegionUtil.setBorderTop(1, region, sheet, wb);
                    RegionUtil.setBottomBorderColor(IndexedColors.BLACK.index, region, sheet, wb);
                    RegionUtil.setLeftBorderColor(IndexedColors.BLACK.index, region, sheet, wb);
                    RegionUtil.setRightBorderColor(IndexedColors.BLACK.index, region, sheet, wb);
                    RegionUtil.setTopBorderColor(IndexedColors.BLACK.index, region, sheet, wb);
                }
            }
        }
        OutputStream output = response.getOutputStream();
        response.reset();
        response.setHeader(
                "Content-Disposition", "attachment;filename=" + URLEncoder.encode("订单列表.xls", "utf-8"));
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        String scrmH5Url = systemProperties.getAcsScrmWebUrl();
        if (scrmH5Url.endsWith("/")) {
            scrmH5Url = scrmH5Url.substring(0, scrmH5Url.length() - 1);
        }
        response.setHeader("Access-Control-Allow-Origin", scrmH5Url);
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        response.addHeader("Access-Control-Allow-Headers", "Content-Type");
        response.setCharacterEncoding("utf-8");
        wb.write(output);
        output.close();
    }

    public List<Map<String, Object>> mallsList(Map<String, Object> params) {
        List<Map<String, Object>> mallsList = shopOrderMapper.getMallsList(params);
        for (Map<String, Object> malls : mallsList) {
            String addressPhone = (String) malls.get("addressPhone");
            if (StringUtils.isEmpty(addressPhone)) {
                String customerId = (String) malls.get("customerId");
                String bindPhone = mallBoomDao.getBindPhoneByCid(customerId);
                malls.put("addressPhone", bindPhone);
            }
            params.put("orderId", malls.get("orderId"));
            List<Map<String, Object>> orderGoodsList = shopOrderMapper.getMallsOrderGoodsList(params);
            if (orderGoodsList != null && orderGoodsList.size() > 0) {
                for (Map<String, Object> orderGoods : orderGoodsList) {
                    // 撤销退款状态改为7
                    if (orderGoods.get("refundStatus") != null
                            && "0".equals(orderGoods.get("refundStatus"))
                            && !StringUtils.isEmpty(orderGoods.get("protectCode"))) {
                        orderGoods.put("refundStatus", 7);
                    }
                }
            }
            malls.put("goodsList", orderGoodsList);
        }
        return mallsList;
    }

    public Map<String, Object> getMallsOrder(Map<String, Object> params) {
        Map<String, Object> result = shopOrderMapper.getMallsOrder(params);
        if (result != null) {
            // 采购商品列表
            String purchaseSn = (String) result.get("purchaseSn");
            List<Map<String, Object>> orderGoodsList = shopOrderMapper.getMallsOrderGoods(purchaseSn);
            result.put("goodsList", orderGoodsList);
            // 付款信息
            String storeName = shopOrderMapper.getPayInfo(result);
            result.put("storeName", storeName);
            // 供货商信息
            Map<String, Object> mallsInfo = shopOrderMapper.getMallsInfo(result);
            result.put("mallName", mallsInfo.get("mallName"));
            result.put("mallPhone", mallsInfo.get("mallPhone"));
            result.put("mallTelephone", mallsInfo.get("mallTelephone"));
            return result;
        } else {
            throw GlobalException.build("暂无该采购订单，或者已删除");
        }
    }

    public void exportMallsList(
            Map<String, Object> params, HttpServletResponse response, Integer payMode) {
        List<Map<String, Object>> mallsList = shopOrderMapper.getMallsList(params);
        for (Map<String, Object> malls : mallsList) {
            String addressPhone = (String) malls.get("addressPhone");
            if (StringUtils.isEmpty(addressPhone)) {
                String customerId = (String) malls.get("customerId");
                String bindPhone = mallBoomDao.getBindPhoneByCid(customerId);
                malls.put("addressPhone", bindPhone);
            }
            params.put("orderId", malls.get("orderId"));
            List<Map<String, Object>> orderGoodsList = shopOrderMapper.getMallsOrderGoodsList(params);
            if (orderGoodsList != null && orderGoodsList.size() > 0) {
                for (Map<String, Object> orderGoods : orderGoodsList) {
                    // 撤销退款状态改为7
                    if (orderGoods.get("refundStatus") != null
                            && "0".equals(orderGoods.get("refundStatus"))
                            && !StringUtils.isEmpty(orderGoods.get("protectCode"))) {
                        orderGoods.put("refundStatus", 7);
                    }
                }
            }
            malls.put("goodsList", orderGoodsList);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
        String date = sdf.format(new Date());
        String title = "采购订单" + date;
        try {
            exportMallsXls(title, response, mallsList, payMode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void exportMallsXls(
            String title1,
            HttpServletResponse response,
            List<Map<String, Object>> mallsList,
            Integer payMode)
            throws Exception {
        // 第一步，创建一个HSSFWorkbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();

        // 第二步，在workbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet(title1);
        for (int i = 0; i < 47; i++) {
            sheet.setColumnWidth(i, 256 * 20 + 184);
        }
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
        HSSFRow row = sheet.createRow(0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle cellStyle = wb.createCellStyle();
        // 设置背景色
        cellStyle.setFillForegroundColor((short) 13);
        cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

        cellStyle.setBottomBorderColor(IndexedColors.BLACK.index);
        cellStyle.setTopBorderColor(IndexedColors.BLACK.index);
        cellStyle.setLeftBorderColor(IndexedColors.BLACK.index);
        cellStyle.setRightBorderColor(IndexedColors.BLACK.index);
        // 下边框
        cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        // 左边框
        cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 上边框
        cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 右边框
        cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);

        // HSSFCellStyle style = wb.createCellStyle();
        // 创建一个居中格式
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        HSSFCellStyle cellStyleR = wb.createCellStyle();
        cellStyleR.setBottomBorderColor(IndexedColors.BLACK.index);
        cellStyleR.setTopBorderColor(IndexedColors.BLACK.index);
        cellStyleR.setLeftBorderColor(IndexedColors.BLACK.index);
        cellStyleR.setRightBorderColor(IndexedColors.BLACK.index);
        cellStyleR.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        cellStyleR.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        cellStyleR.setBorderTop(HSSFCellStyle.BORDER_THIN);
        cellStyleR.setBorderRight(HSSFCellStyle.BORDER_THIN);

        // HSSFCellStyle style = wb.createCellStyle();
        // 创建一个居中格式
        cellStyleR.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        HSSFFont font = wb.createFont();
        font.setFontName("黑体");
        // 设置字体大小
        font.setFontHeightInPoints((short) 14);
        cellStyle.setFont(font);
        // 声明列对象
        HSSFCell cell = null;
        String[] title = {
                "采购时间", "采购订单", "买家订单号", "商品名称", "单价", "数量", "规格", "买家", "买家手机号", "采购实付", "状态"
        };
        // 创建标题
        for (int i = 0; i < title.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(cellStyle);
        }
        for (int i = 0; i < title.length; i++) {
            Integer startrow = 0;
            Integer overrow = 0;
            Integer startcol = i;
            Integer overcol = i;
            sheet.addMergedRegion(new CellRangeAddress(startrow, overrow, startcol, overcol));
        }

        int count = 1;
        for (Map<String, Object> order : mallsList) {
            List<Map<String, Object>> goodslist = (List<Map<String, Object>>) order.get("goodsList");
            if (goodslist != null && goodslist.size() > 0) {
                int starcount = count;
                int endcount = count + goodslist.size() - 1;
                row = sheet.createRow(count);
                cell = row.createCell(0);
                cell.setCellStyle(cellStyleR);
                String paymentTime = "";
                if (!StringUtils.isEmpty(order.get("paymentTime"))) {
                    paymentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(order.get("paymentTime"));
                }
                cell.setCellValue(paymentTime);
                cell = row.createCell(1);
                cell.setCellStyle(cellStyleR);
                cell.setCellValue((String) order.get("purchaseSn"));
                cell = row.createCell(2);
                cell.setCellStyle(cellStyleR);
                cell.setCellValue((String) order.get("orderSn"));

                cell = row.createCell(7);
                cell.setCellStyle(cellStyleR);
                cell.setCellValue((String) order.get("userNickName"));
                cell = row.createCell(8);
                cell.setCellStyle(cellStyleR);
                cell.setCellValue((String) order.get("addressPhone"));
                cell = row.createCell(9);
                cell.setCellStyle(cellStyleR);
                cell.setCellValue((String) order.get("orderTotalPrice"));
                cell = row.createCell(10);
                cell.setCellStyle(cellStyleR);
                String orderStatus = "";
                switch ((Integer) order.get("status")) {
                    case 0:
                        orderStatus = "已关闭";
                        break;
                    case 10:
                        orderStatus = "待付款";
                        break;
                    case 20:
                        orderStatus = "待发货";
                        break;
                    case 30:
                        orderStatus = "待收货";
                        break;
                    case 40:
                        orderStatus = "交易完成";
                        break;
                    case 50:
                        orderStatus = "已提交";
                        break;
                    case 60:
                        orderStatus = "已确认";
                        break;
                }
                cell.setCellValue(orderStatus);

                for (int j = 0; j < goodslist.size(); j++) {
                    if (j > 0) {
                        row = sheet.createRow(count);
                    }
                    // 前四个是商品的信息
                    cell = row.createCell(3);
                    cell.setCellStyle(cellStyleR);
                    cell.setCellValue((String) goodslist.get(j).get("goodsName"));
                    cell = row.createCell(4);
                    cell.setCellStyle(cellStyleR);
                    cell.setCellValue((String) goodslist.get(j).get("goodsPrice"));
                    cell = row.createCell(5);
                    cell.setCellStyle(cellStyleR);
                    cell.setCellValue((Long) goodslist.get(j).get("goodsNum"));
                    cell = row.createCell(6);
                    cell.setCellStyle(cellStyleR);
                    cell.setCellValue((String) goodslist.get(j).get("skuInfo"));
                    count++;
                }
                for (int i = 0; i < 11; i++) {
                    if(i>2 && i<7){
                        continue;
                    }
                    CellRangeAddress region = new CellRangeAddress(starcount, endcount, i,
                            i);
                    sheet.addMergedRegion(region);
                    // 下边框   左边框  有边框  上边框
                    RegionUtil.setBorderBottom(1, region, sheet, wb);
                    RegionUtil.setBorderLeft(1, region, sheet, wb);
                    RegionUtil.setBorderRight(1, region, sheet, wb);
                    RegionUtil.setBorderTop(1, region, sheet, wb);
                    RegionUtil.setBottomBorderColor(IndexedColors.BLACK.index, region,
                            sheet, wb);
                    RegionUtil.setLeftBorderColor(IndexedColors.BLACK.index, region,
                            sheet, wb);
                    RegionUtil.setRightBorderColor(IndexedColors.BLACK.index, region,
                            sheet, wb);
                    RegionUtil.setTopBorderColor(IndexedColors.BLACK.index, region, sheet,
                            wb);
                }
            }
        }
        OutputStream output = response.getOutputStream();
        response.reset();
        response.setHeader(
                "Content-Disposition", "attachment;filename=" + URLEncoder.encode("采购订单列表.xls", "utf-8"));
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        String scrmH5Url =
                payMode == 0 ? systemProperties.getScrmWebUrl() : systemProperties.getAcsScrmWebUrl();
        if (scrmH5Url.endsWith("/")) {
            scrmH5Url = scrmH5Url.substring(0, scrmH5Url.length() - 1);
        }
        response.setHeader("Access-Control-Allow-Origin", scrmH5Url);
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        response.addHeader("Access-Control-Allow-Headers", "Content-Type");
        response.setCharacterEncoding("utf-8");
        wb.write(output);
        output.close();
    }

    public Map<String, Object> getRefundInfo(Integer recId) {
        Map<String, Object> result = shopOrderMapper.getRefundInfo(recId);
        if (result == null) {
            throw GlobalException.build("查不到退款信息");
        }
        Long refundAmount = protectRecordDao.getAllAmountByRecId(Long.valueOf(recId.toString()));
        String refundAmountStrig = "0.00";
        if(refundAmount!=null){
            refundAmountStrig = NumberUtils.fenToYuan(refundAmount);
        }
        result.put("refundAmount",refundAmountStrig);
        List<Map<String, Object>> list = shopOrderMapper.getRefundInfoList(recId);
        result.put("list", list);
        return result;
    }

    public void againRefund(Map<String, Object> params) {
        String key = "refund:againRefund" + params.get("protectCode");
        String orderPay = stringRedisTemplate.opsForValue().getAndSet(key, "1");
        stringRedisTemplate.expire(key, 10, TimeUnit.SECONDS);
        if (StringUtils.isEmpty(orderPay)) {
            RefundParamPo rePo = refundDao.getRefundParamPo(params);
            Map<String, Object> temps = new HashMap<>();
            temps.put("recId", rePo.getRecId());
            temps.put("remark", "重新发起退款");
            temps.put("status", 1);
            purchaseProcessDao.addRefundLogs(temps);
            // 调用退款接口
            Map<String, String> res = new HashMap<>();
            try {
                if (rePo.getPayType() != null && rePo.getPayType() == 1) {
                    // 微信支付
                    Long refundAmount = protectRecordDao.getAllAmountByRecId(rePo.getRecId());
                    if (refundAmount > 0) {
                        res =
                                purchaseProcessService.refund(
                                        rePo.getOrderSn(),
                                        rePo.getRefundReason(),
                                        (new Long(refundAmount).intValue()),
                                        rePo.getPaySn());
                    }
                    // 返回参数入库用于查询退款结果
                    if (res != null && res.size() > 0) {
                        res.put("protectCode", rePo.getProtectCode());
                        refundDao.updaterefundAgg(res);
                    }
                } else if (rePo.getPayType() != null && rePo.getPayType() != 1) {
                    refundService.newTlRefund(rePo, rePo.getPayType());
                }
            } catch (Exception e) {
                Map<String, Object> temp = new HashMap<>();
                temp.put("recId", rePo.getRecId());
                temp.put("remark", "退款失败");
                temp.put("status", 3);
                purchaseProcessDao.addRefundLogs(temp);
            }
        }
    }


    public List<ShopOrder> lostList(Map<String, Object> params) {
        // 当前用户
        String belongId = params.get("belongId").toString();
        List<ShopOrder> orderList = shopOrderMapper.getLossOrderList(params);
        for (ShopOrder order : orderList) {
            String addressPhone = order.getAddressPhone();
            if (StringUtils.isEmpty(addressPhone)) {
                String customerId = order.getCustomerId();
                String bindPhone = mallBoomDao.getBindPhoneByCid(customerId);
                order.setAddressPhone(bindPhone);
            }
            String createTime = order.getCreateTime();
            if (createTime.contains(".")) {
                String substring = createTime.substring(0, createTime.length() - 2);
                order.setCreateTime(substring);
            }
            //  订单类型
            String orderType = "";
            if (1 == order.getOrderGoodsType()) {
                // 实物订单
                orderType = orderType + "/" + "实物订单";
            } else {
                // 课程订单
                orderType = orderType + "/" + "课程订单";
            }
            order.setOrderGoodsType2(0);
            // 供货商品
            if (belongId.equals(order.getSalerBelongId())
                    && !StringUtils.isEmpty(order.getMallsBelongId())) {
                // 推广订单
                orderType = orderType + "/" + "推广订单";
                order.setOrderGoodsType2(1);
            }
            if (belongId.equals(order.getMallsBelongId())) {
                // 供货订单
                orderType = orderType + "/" + "供货订单";
                order.setOrderGoodsType2(2);
            }
            if (!belongId.equals(order.getSalerBelongId())
                    && !belongId.equals(order.getMallsBelongId())) {
                orderType = orderType + "/" + "联盟商家订单";
                order.setOrderGoodsType2(3);
            }
            if (StringUtils.isEmpty(orderType)) {
                orderType = "/";
            }
            order.setOrderType(orderType.substring(1));
            // 供货名称
            String supplyName = "";
            if (3 == order.getOrderGoodsType2()) {
                // 联盟商家订单
                supplyName = shopOrderMapper.getSalerNameByCustomerId(order.getSalerBelongId());
            } else if (1 == order.getOrderGoodsType2()) {
                // 推广订单
                supplyName = shopOrderMapper.getMallsNameByCustomerId(order.getMallsBelongId());
            }
            order.setSupplyName(supplyName);
            //  订单商品
            params.put("orderId", order.getOrderId());
            params.put("orderGoodsType",order.getOrderGoodsType2());
            List<OrderGoods> orderGoodsList = shopOrderMapper.getOrderGoodsList(params);
            if (orderGoodsList != null && orderGoodsList.size() > 0) {
                for (OrderGoods orderGoods : orderGoodsList) {
                    // 撤销退款状态改为7
                    if (orderGoods.getRefundStatus() != null
                            && orderGoods.getRefundStatus() == 0
                            && !StringUtils.isEmpty(orderGoods.getProtectCode())) {
                        orderGoods.setRefundStatus(7);
                    }
                }
            }
            order.setGoodsList(orderGoodsList);
            String orderSn = order.getOrderSn();
            //计算订单收入
            String orderIncome = shopOrderMapper.getOrderIncome(orderSn,belongId);
            //计算订单支出
            String orderExpend = shopOrderMapper.getOrderExpend(orderSn,belongId);
            order.setOrderIncome(orderIncome);
            order.setOrderExpend(orderExpend);
            Integer isEnd = order.getIsEnd();
            if(isEnd==0){
                String lossAmount = order.getLossAmount();
                if(2 == order.getOrderGoodsType2()){
                    //如果供货商充值等于供货商亏损
                    if(lossAmount.equals(order.getMallsRecharge())){
                        order.setIsEnd(1);
                    }
                }else {
                    //如果销售商充值等于销售商亏损
                    if(lossAmount.equals(order.getSalerRecharge())){
                        order.setIsEnd(1);
                    }
                }
            }
        }
        return orderList;
    }

    public void exportLossList(Map<String, Object> params, HttpServletResponse response) {
        // 当前用户
        String belongId = params.get("belongId").toString();
        List<ShopOrder> orderList = shopOrderMapper.getLossOrderList(params);
        for (ShopOrder order : orderList) {
            String addressPhone = order.getAddressPhone();
            if (StringUtils.isEmpty(addressPhone)) {
                String customerId = order.getCustomerId();
                String bindPhone = mallBoomDao.getBindPhoneByCid(customerId);
                order.setAddressPhone(bindPhone);
            }
            String createTime = order.getCreateTime();
            if (createTime.contains(".")) {
                String substring = createTime.substring(0, createTime.length() - 2);
                order.setCreateTime(substring);
            }
            //  订单类型
            String orderType = "";
            if (1 == order.getOrderGoodsType()) {
                // 实物订单
                orderType = orderType + "/" + "实物订单";
            } else {
                // 课程订单
                orderType = orderType + "/" + "课程订单";
            }
            order.setOrderGoodsType2(0);
            // 供货商品
            if (belongId.equals(order.getSalerBelongId())
                    && !StringUtils.isEmpty(order.getMallsBelongId())) {
                // 推广订单
                orderType = orderType + "/" + "推广订单";
                order.setOrderGoodsType2(1);
            }
            if (belongId.equals(order.getMallsBelongId())) {
                // 供货订单
                orderType = orderType + "/" + "供货订单";
                order.setOrderGoodsType2(2);
            }
            if (!belongId.equals(order.getSalerBelongId())
                    && !belongId.equals(order.getMallsBelongId())) {
                orderType = orderType + "/" + "联盟商家订单";
                order.setOrderGoodsType2(3);
            }
            if (StringUtils.isEmpty(orderType)) {
                orderType = "/";
            }
            order.setOrderType(orderType.substring(1));
            // 供货名称
            String supplyName = "";
            if (3 == order.getOrderGoodsType2()) {
                // 联盟商家订单
                supplyName = shopOrderMapper.getSalerNameByCustomerId(order.getSalerBelongId());
            } else if (1 == order.getOrderGoodsType2()) {
                // 推广订单
                supplyName = shopOrderMapper.getMallsNameByCustomerId(order.getMallsBelongId());
            }
            order.setSupplyName(supplyName);
            //  订单商品
            params.put("orderId", order.getOrderId());
            params.put("orderGoodsType",order.getOrderGoodsType2());
            List<OrderGoods> orderGoodsList = shopOrderMapper.getOrderGoodsList(params);
            if (orderGoodsList != null && orderGoodsList.size() > 0) {
                for (OrderGoods orderGoods : orderGoodsList) {
                    // 撤销退款状态改为7
                    if (orderGoods.getRefundStatus() != null
                            && orderGoods.getRefundStatus() == 0
                            && !StringUtils.isEmpty(orderGoods.getProtectCode())) {
                        orderGoods.setRefundStatus(7);
                    }
                }
            }
            order.setGoodsList(orderGoodsList);
            String orderSn = order.getOrderSn();
            //计算订单收入
            String orderIncome = shopOrderMapper.getOrderIncome(orderSn,belongId);
            //计算订单支出
            String orderExpend = shopOrderMapper.getOrderExpend(orderSn,belongId);
            order.setOrderIncome(orderIncome);
            order.setOrderExpend(orderExpend);
            Integer isEnd = order.getIsEnd();
            if(isEnd==0){
                String lossAmount = order.getLossAmount();
                if(2 == order.getOrderGoodsType2()){
                    //如果供货商充值等于供货商亏损
                    if(lossAmount.equals(order.getMallsRecharge())){
                        order.setIsEnd(1);
                    }
                }else {
                    //如果销售商充值等于销售商亏损
                    if(lossAmount.equals(order.getSalerRecharge())){
                        order.setIsEnd(1);
                    }
                }
            }
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
        String date = sdf.format(new Date());
        String title = "待结算订单" + date;
        try {
            exportLossRegisterXls(title, response, orderList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void exportLossRegisterXls(
            String title1, HttpServletResponse response, List<ShopOrder> orderList)
            throws Exception {
        // 第一步，创建一个HSSFWorkbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();

        // 第二步，在workbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet(title1);
        for (int i = 0; i < 47; i++) {
            sheet.setColumnWidth(i, 256 * 20 + 184);
        }
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
        HSSFRow row = sheet.createRow(0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle cellStyle = wb.createCellStyle();
        // 设置背景色
        cellStyle.setFillForegroundColor((short) 13);
        cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

        cellStyle.setBottomBorderColor(IndexedColors.BLACK.index);
        cellStyle.setTopBorderColor(IndexedColors.BLACK.index);
        cellStyle.setLeftBorderColor(IndexedColors.BLACK.index);
        cellStyle.setRightBorderColor(IndexedColors.BLACK.index);
        // 下边框
        cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        // 左边框
        cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 上边框
        cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 右边框
        cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);

        // HSSFCellStyle style = wb.createCellStyle();
        // 创建一个居中格式
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        HSSFCellStyle cellStyleR = wb.createCellStyle();
        cellStyleR.setBottomBorderColor(IndexedColors.BLACK.index);
        cellStyleR.setTopBorderColor(IndexedColors.BLACK.index);
        cellStyleR.setLeftBorderColor(IndexedColors.BLACK.index);
        cellStyleR.setRightBorderColor(IndexedColors.BLACK.index);
        cellStyleR.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        cellStyleR.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        cellStyleR.setBorderTop(HSSFCellStyle.BORDER_THIN);
        cellStyleR.setBorderRight(HSSFCellStyle.BORDER_THIN);

        // HSSFCellStyle style = wb.createCellStyle();
        // 创建一个居中格式
        cellStyleR.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        HSSFFont font = wb.createFont();
        font.setFontName("黑体");
        // 设置字体大小
        font.setFontHeightInPoints((short) 14);
        cellStyle.setFont(font);
        // 声明列对象
        HSSFCell cell = null;
        String[] title = {
                "商品名称", "单价(元) / 数量" ,"买家", "用户实付金额", "订单收入","订单支出", "结算差额", "状态", "订单号",
                "下单时间", "订单类型"
        };
        // 创建标题
        for (int i = 0; i < title.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(cellStyle);
        }
        for (int i = 0; i < title.length; i++) {
            Integer startrow = 0;
            Integer overrow = 0;
            Integer startcol = i;
            Integer overcol = i;
            sheet.addMergedRegion(new CellRangeAddress(startrow, overrow, startcol, overcol));
        }

        int count = 1;
        for (ShopOrder order : orderList) {
            List<OrderGoods> goodslist = order.getGoodsList();
            if (goodslist != null && goodslist.size() > 0) {
                int starcount = count;
                int endcount = count + goodslist.size() - 1;
                row = sheet.createRow(count);
                cell = row.createCell(2);
                cell.setCellStyle(cellStyleR);
                cell.setCellValue(order.getRealName());
                cell = row.createCell(3);
                cell.setCellStyle(cellStyleR);
                cell.setCellValue(order.getOrderTotalPrice());
                cell = row.createCell(4);
                cell.setCellStyle(cellStyleR);
                cell.setCellValue(order.getOrderIncome());
                cell = row.createCell(5);
                cell.setCellStyle(cellStyleR);
                cell.setCellValue(order.getOrderExpend());
                cell = row.createCell(6);
                cell.setCellStyle(cellStyleR);
                cell.setCellValue(order.getLossAmount());
                cell = row.createCell(7);
                cell.setCellStyle(cellStyleR);
                String orderStatus = "";
                switch (order.getIsEnd()) {
                    case 0:
                        orderStatus = "待结算";
                        break;
                    case 1:
                        orderStatus = "已结算";
                        break;
                    case 3:
                        orderStatus = "充值中";
                        break;
                }
                cell.setCellValue(orderStatus);
                cell = row.createCell(8);
                cell.setCellStyle(cellStyleR);
                cell.setCellValue(order.getOrderSn());
                cell = row.createCell(9);
                cell.setCellStyle(cellStyleR);
                cell.setCellValue(order.getCreateTime());
                cell = row.createCell(10);
                cell.setCellStyle(cellStyleR);
                cell.setCellValue(order.getOrderType());

                for (int j = 0; j < goodslist.size(); j++) {
                    if (j > 0) {
                        row = sheet.createRow(count);
                    }
                    // 前2个是商品的信息
                    cell = row.createCell(0);
                    cell.setCellStyle(cellStyleR);
                    cell.setCellValue(goodslist.get(j).getGoodsName());
                    cell = row.createCell(1);
                    cell.setCellStyle(cellStyleR);
                    cell.setCellValue(goodslist.get(j).getGoodsPrice()+"/"+goodslist.get(j).getGoodsNum());
                    count++;
                }
                for (int i = 2; i < 11; i++) {
                    CellRangeAddress region = new CellRangeAddress(starcount, endcount, i, i);
                    sheet.addMergedRegion(region);
                    // 下边框   左边框  有边框  上边框
                    RegionUtil.setBorderBottom(1, region, sheet, wb);
                    RegionUtil.setBorderLeft(1, region, sheet, wb);
                    RegionUtil.setBorderRight(1, region, sheet, wb);
                    RegionUtil.setBorderTop(1, region, sheet, wb);
                    RegionUtil.setBottomBorderColor(IndexedColors.BLACK.index, region, sheet, wb);
                    RegionUtil.setLeftBorderColor(IndexedColors.BLACK.index, region, sheet, wb);
                    RegionUtil.setRightBorderColor(IndexedColors.BLACK.index, region, sheet, wb);
                    RegionUtil.setTopBorderColor(IndexedColors.BLACK.index, region, sheet, wb);
                }
            }
        }
        OutputStream output = response.getOutputStream();
        response.reset();
        response.setHeader(
                "Content-Disposition", "attachment;filename=" + URLEncoder.encode("待结算订单列表.xls", "utf-8"));
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        String scrmH5Url = systemProperties.getAcsScrmWebUrl();
        if (scrmH5Url.endsWith("/")) {
            scrmH5Url = scrmH5Url.substring(0, scrmH5Url.length() - 1);
        }
        response.setHeader("Access-Control-Allow-Origin", scrmH5Url);
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        response.addHeader("Access-Control-Allow-Headers", "Content-Type");
        response.setCharacterEncoding("utf-8");
        wb.write(output);
        output.close();
    }

    public String getMerchantCustomerIdByMallsName(String mallsName) {
        return shopOrderMapper.getMerchantCustomerIdByMallsName(mallsName);
    }
}
